package com.christianposta.learnddd.domain.model.location;

import java.util.regex.Pattern;

import org.apache.commons.lang.Validate;

import com.christianposta.learnddd.domain.shared.ValueObject;

public class UnLocode implements ValueObject<UnLocode> {

	private String unlocode;
	
	/*
	 * Needed by Hibernate?
	 */
	private UnLocode(){
		
	}

	private static final Pattern VALID_PATTERN = Pattern
			.compile("[a-zA-Z]{2}[a-zA-z2-9]{3}");

	public UnLocode(final String countryAndLocation) {
		Validate.notNull(countryAndLocation,
				"Country and location param cannot be null");
		Validate.isTrue(VALID_PATTERN.matcher(countryAndLocation).matches(),
				countryAndLocation
						+ " is not a valid UN/LOCODE (does not match pattern)");

		this.unlocode = countryAndLocation.toUpperCase();
	}

	public boolean sameValueAs(UnLocode other) {
		return other != null && this.unlocode.equals(other.unlocode);
	}

	public String idString() {
		return unlocode;
	}

	@Override
	public int hashCode() {
		return unlocode.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UnLocode other = (UnLocode) obj;
		return sameValueAs(other);
	}
	
	

}
